<template>
  <div class="container">
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="小智同学"
    ></van-nav-bar>
    <!-- 智能对话：聊天区域 -->
    <div class="chat-list" ref="list">
      <!-- 左边：小智同学 -->
      <div
        class="chat-item"
        :class="{ left: item.name === 'xz', right: item.name === 'my' }"
        v-for="(item, i) in list"
        :key="i"
      >
        <van-image fit="cover" v-if="item.name === 'xz'" round :src="xzTx" />
        <div class="chat-pao">{{ item.msg }}</div>
        <van-image fit="cover" v-if="item.name === 'my'" round :src="photo" />
      </div>
      <!-- 自己：当前登录人 -->
      <!-- <div class="chat-item right">
        <div class="chat-pao">ewqewq</div>
        <van-image fit="cover" round :src="photo" />
      </div> -->
    </div>
    <!-- 我：提问区域 -->
    <div class="reply-container van-hairline--top">
      <van-field v-model="value" placeholder="说点什么...">
        <span @click="send()" slot="button" style="font-size: 12px; color: #999"
          >提交</span
        >
      </van-field>
    </div>
  </div>
</template>

<script>
// 引入图片资源:1. import 2. require
import xzTx from '../../assets/images/xz.png'
// 获取vuex里store中定义的state数据
import { mapState } from 'vuex'
// 导入插件IO方法
import io from 'socket.io-client'

export default {
  data () {
    return {
      value: '',
      xzTx,
      // xzTx: require('../../assets/images/xz.png')
      // 聊天列表数据=>设计数据结构：[{name:'xz',msg:'你好！'},{name:'my',msg:'你好！小智！'}]
      list: []
    }
  },
  computed: {
    ...mapState(['photo', 'user'])
  },
  created () {
    // this.nativeWS()
    this.initWs()
  },
  // 组件销毁之前关闭socket连接
  beforeDestroy () {
    this.socket.close()
  },
  methods: {
    send () {
      // 发消息
      // this.myWs.send(this.value)
      // 使用IO插件提供的emit方法（参数：1. 自定义事件名字（一般由后台定义）2. 发送数据）
      this.socket.emit('message', { msg: this.value, name: '小刚', timestamp: +new Date() })
      // 显示到界面中
      this.list.push({ name: 'my', msg: this.value })
      // 清空输入内容
      this.value = ''
    },
    // 滚动聊天列表到底部
    goBottom () {
      // 异步渲染完界面后执行滚动
      this.$nextTick(() => {
        const list = this.$refs.list
        list.scrollTop = list.scrollHeight
      })
    },
    // 使用IO插件初始化WS
    initWs () {
      // 初始化WS => new WebSocket('url')
      this.socket = io('http://localhost:3000', {
        query: {
          token: this.user.token
        }
      })
      // 建立连接的事件
      this.socket.on('connect', () => {
        console.log(
          '建立连接成功！'
        )
        // 小智同学们=》主动说句话
        this.list.push({ name: 'xz', msg: '你好！有什么可以帮助你？' })
      })
      // 接收WS服务器的数据
      this.socket.on('message', (data) => {
        // 显示到界面中
        this.list.push({ name: 'xz', msg: data.msg })
        // 滚动到底部
        this.goBottom()
      })
    },
    // 原生js使用WebSocket通信=》打电话
    nativeWS () {
      // WS地址：ws://echo.websocket.org
      // 1. 初始化WS对象=>建立连接
      this.myWs = new WebSocket('ws://echo.websocket.org')
      console.log(this.myWs)
      // 2. 建立连接成功对事件
      this.myWs.onopen = (e) => {
        console.log('和ws://echo.websocket.org建立长连接成功：', e)
        // 给WS服务器发消息
        this.myWs.send('hello ws!')
        // 关闭连接
        this.myWs.close()
      }
      // 获取服务器给客户端浏览器发送的消息
      this.myWs.onmessage = (e) => {
        console.log('获取服务器给客户端浏览器发的消息：', e.data)
      }

      // 关闭WS时触发
      this.myWs.onclose = () => {
        console.log('WS关闭了！')
      }
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
